package com.example.mailbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mailbackend.entity.Role;
import com.example.mailbackend.mapper.RoleDao;
import com.example.mailbackend.mapper.UserDao;
import com.example.mailbackend.entity.User;
import com.example.mailbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2024-01-17 19:23:06
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService, UserDetailsService {
    @Autowired
    RoleDao roleDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(User::getUsername,username); //select * from where username=#{username}
        User user = baseMapper.selectOne(queryWrapper);
        if(user==null){
            throw new UsernameNotFoundException("账号或密码错误");
        }
        List<Role> roles = roleDao.getByuid(user.getId());
        List<String> list = roles.stream().map(Role::getName).toList();
        user.setAuthorities(AuthorityUtils.createAuthorityList(list));
        return user;
    }
}

